<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? 'Add新增' : 'Update修改'" width="70%" :close-on-click-modal="false">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" :inline="true" label-width="160px" @keyup.enter="submitHandle()">
			<el-form-item prop="inventoryDate" label="Inventorydate 入库日期">
				<el-date-picker
					v-model="dataForm.inventoryDate"
					type="date"
					placeholder="please choose"
					:shortcuts="store.commonStore.shortcuts"
					value-format="YYYY-MM-DD HH:mm:ss"
				/>
			</el-form-item>
			<el-form-item prop="pickupDate" label="PickupDate 提货日期">
				<el-date-picker
					v-model="dataForm.pickupDate"
					align="right"
					type="date"
					placeholder="please choose"
					:shortcuts="store.commonStore.shortcuts"
					value-format="YYYY-MM-DD HH:mm:ss"
				/>
			</el-form-item>
			<el-form-item prop="pickupDestination" label="Pickup destination提货目的地" label-width="230px">
				<el-select v-model="dataForm.pickupDestination" remote :remote-method="getPlaceList"
				 filterable clearable placeholder="please input a keyword">
					<el-option
					v-for="item in placeOptions"
					:key="item.dictTypeId"
					:label="item.dictLabel"
					:value="item.dictValue"
					/>
				</el-select>
			</el-form-item>
			<el-form-item prop="jobNumber" label="JOB NUMBER自编号">
				<el-input v-model="dataForm.jobNumber" placeholder="自编号"></el-input>
			</el-form-item>
			<el-form-item prop="cntNo" label="CTN NO箱号">
				<el-input v-model="dataForm.cntNo" placeholder="please input"></el-input>
			</el-form-item>
			<el-form-item prop="receiptNo" label="System NO收据单号">
				<el-input v-model="dataForm.receiptNo" placeholder="收据单号"></el-input>
			</el-form-item>
			<el-form-item prop="customerId" label="CLEMENT客户">
				<el-select v-model="dataForm.customerId" remote :remote-method="getClientList" value-key="id"
				 filterable clearable placeholder="please input a keyword" @change="customerChange">
					<el-option
					v-for="item in clientOptions"
					:key="item.id"
					:label="item.name"
					:value="item.id"
					/>
				</el-select>
			</el-form-item>
			<el-form-item prop="customerMobile" label="TEL 电话" required>
				<el-input v-model="dataForm.customerMobile" placeholder="电话"></el-input>
			</el-form-item>
			<el-form-item prop="salesName" label="Sales 销售" required>
				<el-input v-model="dataForm.salesName" placeholder="" disabled></el-input>
			</el-form-item>
			<el-form-item prop="csName" label="CS 客服" required>
				<el-input v-model="dataForm.csName" placeholder="" disabled></el-input>
			</el-form-item>
			<el-form-item prop="cnts" label="CTNS 箱数">
				<el-input v-model="dataForm.cnts" placeholder="箱数"></el-input>
			</el-form-item>
			<el-form-item prop="grossWeight" label="GROSS WEIGHT 实重">
				<el-input v-model="dataForm.grossWeight" placeholder=""></el-input>
			</el-form-item>
			<el-form-item prop="chargeWeight" label="CHARGE WEIGHT 计费重" label-width="180px">
				<el-input v-model="dataForm.chargeWeight" placeholder="" @change="changeChargeWeight"></el-input>
			</el-form-item>
			<el-form-item prop="grossWeightUnit" label="grossWeightUnit 重量单位" required label-width="190px">
				<el-select v-model="dataForm.grossWeightUnit"
				 filterable clearable placeholder="please input a keyword">
					<el-option
					v-for="item in unitOptions"
					:key="item.id"
					:label="item.dictLabel"
					:value="item.dictValue"
					/>
				</el-select>
			</el-form-item>
			<el-form-item prop="unitPriceUsd" label="UNIT PRICE USD 美金单价" label-width="190px">
				<el-input v-model="dataForm.unitPriceUsd" placeholder="美金单价" @change="changeUnitPriceUsd"></el-input>
			</el-form-item>
			<el-form-item prop="otherChargeUsd" label="OTHER CHARGE 美金其他费用" label-width="220px">
				<el-input v-model="dataForm.otherChargeUsd" placeholder="please input" @change="changeOtherChargeUsd"></el-input>
			</el-form-item>
			<el-form-item prop="totalUsd" label="TOTAL USD 美金金额">
				<el-input v-model="dataForm.totalUsd" placeholder=""></el-input>
			</el-form-item>
			<el-form-item prop="unitPriceRmb" label="UNIT PRICE 人民币单价" label-width="190px">
				<el-input v-model="dataForm.unitPriceRmb" placeholder="" @change="changeUnitPriceRmb"></el-input>
			</el-form-item>
			<el-form-item prop="otherChargeRmb" label="OTHER CHARGE 人民币其他费用" label-width="230px">
				<el-input v-model="dataForm.otherChargeRmb" placeholder="" @change="changeOtherChargeRmb"></el-input>
			</el-form-item>
			<el-form-item prop="totalRmb" label="TOTAL RMB 人民币金额" label-width="190px">
				<el-input v-model="dataForm.totalRmb" placeholder=""></el-input>
			</el-form-item>
			<el-form-item prop="note" label="NOTE 备注">
				<el-input v-model="dataForm.note" placeholder="备注" type="textarea"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">Cancel 取消</el-button>
			<el-button type="primary" @click="submitHandle()">Confirm 确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { ElMessage } from 'element-plus/es'
import {  useReceiveApi, useReceiveSubmitApi } from '@/api/receivable'
import { getClientListApi, selectCustomerList } from '@/api/client'
import {  useSelectRelListApi } from '@/api/dict'
import store from '@/store'

const props = defineProps({
	salesOptions: {
		type: Array
	},
	csOptions: {
		type: Array
	}
})
const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const dataFormRef = ref()
const dataForm = reactive({
	id: '',
	inventoryDate: '',
	pickupDate: '',
	pickupDestination: '',
	jobNumber: '',
	cntNo: '',
	receiptNo: '',
	customerId: '',
	customerName: '',
	customerMobile: '',
	cnts: '',
	grossWeight: '',
	chargeWeight: '',
	otherChargeUsd: '',
	unitPriceUsd: '',
	totalUsd: '',
	unitPriceRmb: '',
	otherChargeRmb: '',
	totalRmb: '',
	note: '',
	salesId: '',
	salesName: '',
	csId: '',
	csName: '',
	grossWeightUnit: ''
})

// dataForm.totalUsd = computed<string>( () => {
//   return Number(dataForm.chargeWeight) * Number(dataForm.unitPriceUsd) + Number(dataForm.otherChargeUsd) + '';
// })
// dataForm.totalRmb = computed<string>( () => {
//   return Number(dataForm.chargeWeight) * Number(dataForm.unitPriceRmb) + Number(dataForm.otherChargeRmb) + '';
// })

const customerList = reactive([]);

// 表单输入规则限制
const validateNumber = (rule: any, value: any, callback: any) => {
	let isNumber;
	if (value && value !== '') {
		isNumber = value.replace(/[^\d.]/g, "")
			.replace(/\.{2,}/g, ".")
			.replace(".", "$#$")
			.replace(/\./g, "")
			.replace("$#$", ".")
			.replace(/^\./g, "");
		if (isNumber) {
			callback()
		}else{
			callback(new Error('Please input number'))
		}
	}else{
		callback()
	}
}
const dataRules = ref({
	jobNumber: [{ required: true, trigger: 'blur'}],
	receiptNo: [{ required: true, trigger: 'blur'}],
	customerId: [{ required: true, trigger: 'blur'}],
	unitPriceUsd: [{ validator: validateNumber, trigger: 'blur' }],
	otherChargeUsd: [{ validator: validateNumber, trigger: 'blur' }],
	totalUsd: [{ validator: validateNumber, trigger: 'blur' }],
	unitPriceRmb: [{ validator: validateNumber, trigger: 'blur' }],
	otherChargeRmb: [{ validator: validateNumber, trigger: 'blur' }],
	totalRmb: [{ validator: validateNumber, trigger: 'blur' }]
})

const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	// id 存在则为修改
	if (id) {
		getReceiveInfo(id)
	}
}

const getReceiveInfo = (id: number) => {
	useReceiveApi(id).then(res => {
		let obj = { ...res.data };
		Object.assign(dataForm, obj)
	})
}

// 客户选项下拉
const clientOptions = ref([])
const getClientList = (query: string) => {
	let req = {
		page: 1,
		limit: 100,
		customerName: query
	}
	selectCustomerList(req).then(res => {
		clientOptions.value = res.data.list;
	})
}
getClientList('');

// 提货地点、重量单位下拉
const placeOptions = ref([]), unitOptions = ref([]);
const getDictSelectList = (query: string, type: string) => {
	let req = {
		page: 1,
		limit: 100,
		dictType: type,
		dictLabel: query
	}
	useSelectRelListApi(req).then(res => {
		switch(type){
			case 'place': placeOptions.value = res.data; break;
			case 'cargo_unit': unitOptions.value = res.data; break;
		}
	})
}
const getPlaceList = (query: string, type: string) => {
	getDictSelectList(query, 'place');
};
const getUnitList = (query: string, type: string) => {
	getDictSelectList(query, 'cargo_unit');
};
getPlaceList('', 'place');
getUnitList('', 'cargo_unit');

const customerChange = (item) => {
	let arr = clientOptions.value as any;
	for(let val of arr){
		if(val.id === item){
			dataForm.customerMobile = val.mobile;
			dataForm.salesId = val.salesId;
			dataForm.salesName = val.salesName;
			dataForm.csId = val.csId;
			dataForm.csName = val.csName;
		}
	}
}

// 总金额可能会自己修改，无法使用computed
const changeChargeWeight = (val) =>{
	dataForm.totalUsd = Math.round(Number(dataForm.chargeWeight) * Number(dataForm.unitPriceUsd) + Number(dataForm.otherChargeUsd))+'';
	dataForm.totalRmb = Math.round(Number(dataForm.chargeWeight) * Number(dataForm.unitPriceRmb) + Number(dataForm.otherChargeRmb))+ '';
}
const changeUnitPriceUsd = (val) =>{
	dataForm.totalUsd = Math.round(Number(dataForm.chargeWeight) * Number(dataForm.unitPriceUsd) + Number(dataForm.otherChargeUsd))+'';
}
const changeOtherChargeUsd = (val) =>{
	dataForm.totalUsd = Math.round(Number(dataForm.chargeWeight) * Number(dataForm.unitPriceUsd) + Number(dataForm.otherChargeUsd))+'';
}
const changeUnitPriceRmb = (val) =>{
	dataForm.totalRmb = Math.round(Number(dataForm.chargeWeight) * Number(dataForm.unitPriceRmb) + Number(dataForm.otherChargeRmb))+ '';
}
const changeOtherChargeRmb = (val) =>{
	dataForm.totalRmb = Math.round(Number(dataForm.chargeWeight) * Number(dataForm.unitPriceRmb) + Number(dataForm.otherChargeRmb))+ '';
}

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			ElMessage.warning('请先校验输入')
			return false
		}
		let req = {...dataForm};
		useReceiveSubmitApi(req).then(() => {
			ElMessage.success({
				message: 'Success 操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init,
	dataForm
})
</script>
<style scoped>
	.el-form{
		display: flex;
		flex-wrap: wrap;
		justify-content: space-space-between;
	}
	.el-form .el-form-item{
		width: 48%;
	}
</style>
